package com.pansoft.openplanet.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.CircleImageView;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.utilcode.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BottomAssetChooseDialogFragment extends BottomSheetDialogFragment {

    public static final String TAG = "BottomAssetChooseDialogFragment";
    private Context mContext;
    private List<AssetListBean> list = new ArrayList<>();
    private WalletAdapter walletAdapter;
    private String walletAddress;
    private String assetName;

    private OnAssetSelectChangedListener onAssetSelectChangedListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_wallet_choose_popup, container, false);
        initView(rootView);
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
//        getDialog().getWindow()
//                .setLayout(WindowManager.LayoutParams.MATCH_PARENT, 1000);
//        getDialog().getWindow().setGravity(Gravity.BOTTOM);
//        getDialog().setCanceledOnTouchOutside(true);
//        getDialog().setCancelable(true);
    }

    public BottomAssetChooseDialogFragment() {
    }


    private void initView(View contentView) {
        TextView tvTitle = contentView.findViewById(R.id.title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_asset_barcode_receive_replacement_of_assets));
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        walletAdapter = new WalletAdapter(mContext, R.layout.open_planet_item_assetlist_item, list);
        recyclerView.setAdapter(walletAdapter);
        initData();
    }

    /**
     * 请求所有代币列表
     */
    private void initData() {
        //第一个为默认的ETH钱包，不可以操作
        AssetListBean assetListBean0 = new AssetListBean();
        assetListBean0.setName(getString(R.string.ETH_NAME));
        assetListBean0.setSecondName(getString(R.string.ETH_SUB_NAME));
        assetListBean0.setIcon(getString(R.string.ETH_IMG_URL));
//        final String address = EnvironmentVariable.getProperty("tc_ethAddress");
//        if (address.length() > 20) {
//            String formatAddress = address.replace(address.substring(6, address.length() - 4), "****");
//            assetListBean0.setAddress(formatAddress);
//        } else {
        assetListBean0.setAddress(walletAddress);
        // }
        list.add(assetListBean0);

        //请求该链上的所有代币数据
        HashMap<String, String> params = new HashMap<>();
        params.put("chainID", "2");//链编号ETC传2
//        params.put("userAddress", EnvironmentVariable.getProperty("tc_ethAddress"));
        params.put("userAddress", walletAddress);

        TCRequestUtil.getCommonRequest(TAG, "chain/getAllTokenByChain", params,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optString("result").equals("success")) {
                                JSONArray jsonArray = jsonObject.optJSONArray("AllTokenByChain");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject walletObject = jsonArray.getJSONObject(i);
                                        AssetListBean assetListBean = new AssetListBean.Builder()
                                                .address(walletObject.optString("tokenAddress"))
                                                .icon(walletObject.optString("tokenIcon"))
                                                .name(walletObject.optString("tokenName"))
                                                .secondName(walletObject.optString("tokenFullName"))
                                                .balance(walletObject.optString("balance"))
                                                .id(walletObject.optString("tokenID"))
                                                .blockChainID(walletObject.optString("blockChainID"))
                                                .tokenDecimals(walletObject.optInt("tokenDecimals"))
                                                .isSelected(walletObject.optBoolean("isSelected"))
                                                .build();
                                        list.add(assetListBean);
                                    }
                                }
                                walletAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                    }
                });
    }

    public void setData(Context context, String walletAddress, String assetName) {
        this.mContext = context;
        this.walletAddress = walletAddress;
        this.assetName = assetName;
    }


    public class WalletAdapter extends CommonAdapter<AssetListBean> {

        public WalletAdapter(Context context, int layoutId, List<AssetListBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(com.efounder.recycleviewhelper.base.ViewHolder holder, final AssetListBean assetListBean, int position) {

            CircleImageView ivIamge;
            TextView tvName;
            TextView tvName2;
            TextView tvAddress;
            final SwitchCompat switchButton;

            ivIamge = (CircleImageView) holder.getView(R.id.iv_iamge);
            tvName = (TextView) holder.getView(R.id.tv_name);
            tvName2 = (TextView) holder.getView(R.id.tv_name2);
            tvAddress = (TextView) holder.getView(R.id.tv_address);
            switchButton = (SwitchCompat) holder.getView(R.id.switch_button);
            switchButton.setVisibility(View.INVISIBLE);
            LXGlideImageLoader.getInstance().displayImage(mContext, ivIamge, assetListBean.getIcon());
            tvName.setText(assetListBean.getName());
            tvName2.setText(assetListBean.getSecondName());
            //处理地址显示
            String address = assetListBean.getAddress();
            if (address.length() > 20) {
                String formatAddress = address.replace(address.substring(6, address.length() - 4), "****");
                tvAddress.setText(formatAddress);
            } else {
                tvAddress.setText("");
            }

            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onAssetSelectChangedListener != null) {
                        onAssetSelectChangedListener.onAssetChanged(assetListBean);
                        dismiss();
                    }
                }
            });

        }
    }

    public interface OnAssetSelectChangedListener {
        void onAssetChanged(AssetListBean assetListBean);
    }

    public void setOnAssetSelectChangedListener(OnAssetSelectChangedListener onAssetSelectChangedListener) {
        this.onAssetSelectChangedListener = onAssetSelectChangedListener;
    }

}
